from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import random
import time
from threading import Thread


# 创建 Flask 应用
app = Flask(__name__)
app.config['SECRET_KEY'] = '1212121212'
socketio = SocketIO(app)


# 模拟数据生成函数
def generate_random_data():
    """后台线程：生成模拟数据并推送到客户端"""
    while True:
        try:
            # 生成随机数据
            data = {
                'sales': random.randint(1000, 5000),  # 销售额
                'visitors': random.randint(100, 1000),  # 访问量
                'orders': random.randint(50, 200),  # 订单数
                'timestamp': time.strftime('%H:%M:%S')  # 当前时间
            }
            print(data)
            # 推送数据到客户端
            socketio.emit('update_data', data)

            time.sleep(5)  # 每 2 秒生成一次数据
        except Exception as e:
            print(e)



# 首页路由
@app.route('/')
def index():
    return render_template('index.html')


# WebSocket 事件：客户端连接
@socketio.on('connect')
def handle_connect():
    print('Client connected')
    # emit('server_response', {'data': 'Connected to server!'})
    socketio.start_background_task(generate_random_data)

# WebSocket 事件：客户端断开连接
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')


# WebSocket 事件：接收客户端消息
@socketio.on('client_message')
def handle_message(message):
    print('Received message:', message)
    # 将客户端消息广播给所有连接的客户端
    emit('server_response', {'data': message['data']}, broadcast=True)


# 主函数：启动应用
if __name__ == '__main__':
    # 启动后台线程
    Thread(target=generate_random_data, daemon=True).start()
    # 启动 Flask-SocketIO 服务
    socketio.run(app, host='0.0.0.0', port=5000)